"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : 导入导出数据时，主节点网络链路闪断
Create At   : 2021/07/28
@zou_jialiang0505328126
Description :
    1.创建表并插入数据
    2.导出数据
    3.导出数据同时网络链路闪断
    4.导入数据
    5.导入数据同时网络链路闪断
    6.检查数据一致性
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.c成功
    6.checksum结果一致
History     :
"""

import unittest
import os
import time
from yat.test import Node, macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class DiskIOwait(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('----Opengauss_Reliability_Hardware_Case140:开始执行----')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.sta1_root_node = Node(node='Standby1Root')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.tbname = "t_network_140"
        self.restore_file = os.path.join(macro.DB_BACKUP_PATH,
                                         'dump_backup',
                                         'tools_restore_case001.tar')

        self.log.info("-------------获取网卡名---------------")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.primary_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.primary_user_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

        self.log.info('-------------------创建备份路径---------')
        shell_cmd = f'rm -rf {os.path.dirname(self.restore_file)}; ' \
            f'mkdir {os.path.dirname(self.restore_file)}'
        self.log.info(shell_cmd)
        result = self.primary_user_node.sh(shell_cmd).result()
        self.log.info(result)

    def test_main(self):
        text = '----step1: 创建表并插入数据 expect:成功----'
        self.log.info(text)
        sql = f"create table {self.tbname}(i int);" \
            f"insert into {self.tbname} values(generate_series(1,10000));"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result,
                      '执行失败:' + text)
        self.assertIn("INSERT", result, '执行失败:' + text)
        check_sum = f"SELECT CHECKSUM({self.tbname}::TEXT) " \
            f"FROM {self.tbname};"
        check_sum_pri_bef = self.primary_sh.executDbSql(check_sum)
        self.log.info(check_sum_pri_bef)

        text_dump = '----step2:导出数据 expect:成功----'
        self.log.info(text)
        dump_thread = ComThread(
            self.primary_sh.dumpFile,
            args=(self.restore_file, f'-F t -t {self.tbname}', None, False))
        dump_thread.setDaemon(True)
        dump_thread.start()

        cfe_text = '----step3: 导出数据同时网络链路闪断 expect:成功----'
        self.log.info(cfe_text)
        inject_command = f" rNetLink_flash (repeat,duration,interval,dev) " \
            f"values (25,2,5,{self.networkcard})"
        cfe_thread = ComThread(
            self.com.cfe_inject,
            args=(self.primary_root_node, inject_command,))
        cfe_thread.setDaemon(True)
        cfe_thread.start()

        self.log.info("-------------------获取导出结果---------------------")
        dump_thread.join(180)
        result = dump_thread.get_result()
        self.log.info(result)
        self.assertTrue(result, '执行失败:' + text_dump)

        self.log.info("-------------------获取故障结果---------------------")
        cfe_thread.join(600)
        result = cfe_thread.get_result()
        self.log.info(result)
        flg1 = self.constant.cfe_inject_netflash_success_msg \
               in result or \
               'Determining IP information' in result
        self.assertTrue(flg1, '执行失败' + cfe_text)

        text_restore = '----step4:导入数据 expect:成功----'
        self.log.info(text_restore)
        restore_thread = ComThread(self.primary_sh.restoreFile,
                                   args=(self.restore_file, '-c', False, ))
        restore_thread.setDaemon(True)
        restore_thread.start()

        cfe_text = '----step5: 导入数据同时网络链路闪断 expect:成功----'
        self.log.info(cfe_text)
        inject_command = f" rNetLink_flash (repeat,duration,interval,dev) " \
            f"values (25,2,5,{self.networkcard})"
        cfe_thread = ComThread(
            self.com.cfe_inject,
            args=(self.primary_root_node, inject_command,))
        cfe_thread.setDaemon(True)
        cfe_thread.start()

        self.log.info("-------------------获取导入结果---------------------")
        restore_thread.join(180)
        result = restore_thread.get_result()
        self.assertTrue(result, '执行失败:' + text_restore)

        self.log.info("-------------------获取故障结果---------------------")
        cfe_thread.join(600)
        result = cfe_thread.get_result()
        self.log.info(result)
        flg1 = self.constant.cfe_inject_netflash_success_msg \
               in result or \
               'Determining IP information' in result
        self.assertTrue(flg1, '执行失败' + cfe_text)
        time.sleep(10)

        text = '----step6:检查数据一致性 expect:成功----'
        self.log.info(text)
        result = self.sta_1_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        result = self.sta_2_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        nodes_tuple = (self.primary_user_node,
                       self.sta1_dbuser, self.sta2_dbuser)
        flag = self.com.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag, '执行失败:' + text)

        table_dict = self.com.format_sql_result(
            self.primary_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.com.check_data_sample_by_all(select_sql,
                                                     *nodes_tuple)
            self.assertTrue(flag, '执行失败:' + text)
        result1 = self.primary_sh.executDbSql(check_sum)
        self.log.info(result1)
        result2 = self.sta_1_sh.executDbSql(check_sum)
        self.log.info(result2)
        result3 = self.sta_2_sh.executDbSql(check_sum)
        self.log.info(result3)
        self.assertEqual(result1, result2, '执行失败:' + text)
        self.assertEqual(result1, result3, '执行失败:' + text)
        self.assertEqual(result1, check_sum_pri_bef, '执行失败:' + text)

    def tearDown(self):
        time.sleep(5)
        self.log.info("-------------删除表---------------")
        sql = f"drop table if exists {self.tbname}"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.log.info('--------------删除备份文件-----------')
        shell_cmd = f'rm -rf {os.path.dirname(self.restore_file)}'
        self.log.info(shell_cmd)
        result = self.primary_user_node.sh(shell_cmd).result()
        self.log.info(result)
        self.log.info('---Opengauss_Reliability_Hardware_Case140:执行完成---')
